<template>
	<view style="height: 100vh; background-color: #f5f5f5">
		<topLogo></topLogo>
		<view style="padding: 20px 20px; box-sizing: border-box">
			<view
				style="
					display: flex;
					border-bottom: 1px solid #f5f5f5;
					background-color: #fff;
					align-items: center;
					justify-content: space-between;
					padding: 20px;
					border-radius: 8px 8px 0 0;
				"
			>
				<text style="font-weight: 600; font-size: 20px; color: #666666">拍照</text>
				<view @click="back" style="display: flex; border-radius: 3px; padding: 8px 20px; background-color: #0052d9">
					<text style="font-size: 18px; line-height: 22px; color: #fff; margin-right: 9px">返回</text>
					<up-icon name="arrow-left" size="15" color="#fff"></up-icon>
				</view>
			</view>
			<text class="title">人脸识别拍照上传</text>

			<!-- 引入 tracking 组件 -->
			<FaceTracking ref="trackingRef" :width="320" :height="240" :is-active="isTrackerActive" @onPhotoTaken="handlePhotoTaken"></FaceTracking>

			<!-- 控制按钮 -->
			<button class="start-btn" @click="startRecognition" :disabled="isTrackerActive">
				{{ isTrackerActive ? '识别中...' : '开始人脸识别' }}
			</button>

			<!-- 照片预览（可选） -->
			<view v-if="previewImage" class="preview">
				<text>预览照片：</text>
				<image :src="previewImage" mode="aspectFit" class="preview-img"></image>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import topLogo from '@/components/topLogo.vue';
import FaceTracking from '@/components/FaceTracking.vue';

// =========================================================================

// 父页面状态
const isTrackerActive = ref(false); // 控制组件激活状态
const previewImage = ref(''); // 照片预览
const trackingRef = ref(null); // 组件引用

/**
 * 点击按钮开始人脸识别
 */
const startRecognition = () => {
	isTrackerActive.value = true; // 激活组件，开始识别
};

/**
 * 接收组件返回的照片并上传后端
 */
const handlePhotoTaken = async (result) => {
	isTrackerActive.value = false; // 关闭组件激活状态

	if (result.success) {
		previewImage.value = result.data; // 显示预览
		// 调用后端接口上传照片
		await uploadToBackend(result.data);
	} else {
		uni.showToast({ title: result.msg, icon: 'none' });
	}
};

/**
 * 上传照片到后端
 * @param {String} base64Image - 照片的 base64 字符串
 */
const uploadToBackend = async (base64Image) => {
	try {
		// 后端接口地址（替换为你的实际接口）
		const apiUrl = 'https://your-backend.com/upload-face';

		// 发送请求（base64 转 FormData 或直接传字符串，根据后端要求调整）
		const response = await uni.request({
			url: apiUrl,
			method: 'POST',
			header: { 'Content-Type': 'application/json' },
			data: { image: base64Image } // 直接传 base64 字符串
			// 若后端要求 FormData：
			// data: new FormData().append('image', base64ToBlob(base64Image), 'face.jpg')
		});

		if (response.data.code === 200) {
			uni.showToast({ title: '照片上传成功', icon: 'success' });
		} else {
			uni.showToast({ title: '上传失败：' + response.data.msg, icon: 'none' });
		}
	} catch (err) {
		console.error('上传接口调用失败:', err);
		uni.showToast({ title: '网络错误，上传失败', icon: 'none' });
	}
};

/**
 * base64 转 Blob（若后端要求 FormData 格式）
 */
const base64ToBlob = (base64) => {
	const arr = base64.split(',');
	const mime = arr[0].match(/:(.*?);/)[1];
	const bstr = atob(arr[1]);
	let n = bstr.length;
	const u8arr = new Uint8Array(n);
	while (n--) u8arr[n] = bstr.charCodeAt(n);
	return new Blob([u8arr], { type: mime });
};
// =========================================================================
const callBackModal = () => {
	takePhoto.value = true;
	console.log('去拍照页面');
};
const takePhoto = ref(false);
const toTakePhoto = () => {
	// showRes.value = true;
	console.log('去拍照页面');
};
const showEnterNum = ref(false);
const bindClick = () => {
	showEnterNum.value = true;
};
const back = () => {
	uni.navigateBack();
};
const list1 = ref([
	{
		type: 'a',
		list: [
			{ id: 1, name: '安强', count: 42 },
			{ id: 15, name: '艾云', count: 17 },
			{ id: 22, name: '敖鹏', count: 91 },
			{ id: 36, name: '艾琳', count: 63 },
			{ id: 49, name: '安华', count: 28 },
			{ id: 70, name: '安琪', count: 55 }
		]
	},
	{
		type: 'b',
		list: [
			{ id: 2, name: '白峰', count: 71 },
			{ id: 16, name: '包林', count: 38 },
			{ id: 23, name: '柏军', count: 89 },
			{ id: 37, name: '白雪', count: 14 },
			{ id: 50, name: '毕涛', count: 66 },
			{ id: 71, name: '白铭', count: 45 }
		]
	},
	{
		type: 'c',
		list: [
			{ id: 3, name: '曹宇', count: 23 },
			{ id: 17, name: '陈阳', count: 79 },
			{ id: 24, name: '程敏', count: 56 },
			{ id: 38, name: '崔航', count: 31 },
			{ id: 51, name: '蔡雪', count: 82 },
			{ id: 72, name: '陈博', count: 11 }
		]
	},
	{
		type: 'd',
		list: [
			{ id: 4, name: '邓杰', count: 68 },
			{ id: 18, name: '丁磊', count: 27 },
			{ id: 25, name: '杜铭', count: 95 },
			{ id: 39, name: '董伟', count: 19 },
			{ id: 52, name: '邓云', count: 74 }
		]
	},
	{
		type: 'f',
		list: [
			{ id: 5, name: '方强', count: 33 },
			{ id: 19, name: '范琳', count: 88 },
			{ id: 26, name: '傅航', count: 52 },
			{ id: 40, name: '冯晴', count: 77 },
			{ id: 53, name: '费洋', count: 21 }
		]
	},
	{
		type: 'g',
		list: [
			{ id: 6, name: '高翔', count: 47 },
			{ id: 20, name: '郭玥', count: 65 },
			{ id: 27, name: '顾明', count: 82 },
			{ id: 41, name: '龚宇', count: 12 },
			{ id: 54, name: '谷峰', count: 39 }
		]
	},
	{
		type: 'h',
		list: [
			{ id: 7, name: '韩雪', count: 59 },
			{ id: 21, name: '何明', count: 26 },
			{ id: 28, name: '贺馨', count: 98 },
			{ id: 42, name: '洪涛', count: 41 },
			{ id: 55, name: '黄蓉', count: 73 },
			{ id: 73, name: '胡军', count: 53 }
		]
	},
	{
		type: 'j',
		list: [
			{ id: 8, name: '贾明', count: 37 },
			{ id: 29, name: '蒋雯', count: 92 },
			{ id: 43, name: '金宇', count: 44 },
			{ id: 56, name: '姜峰', count: 15 },
			{ id: 74, name: '蒋超', count: 84 }
		]
	},
	{
		type: 'l',
		list: [
			{ id: 9, name: '李涛', count: 58 },
			{ id: 30, name: '林皓', count: 67 },
			{ id: 44, name: '刘洋', count: 29 },
			{ id: 57, name: '龙云', count: 96 },
			{ id: 75, name: '陆远', count: 18 },
			{ id: 84, name: '卢峰', count: 63 },
			{ id: 88, name: '鲁敏', count: 49 }
		]
	},
	{
		type: 'm',
		list: [
			{ id: 10, name: '马云', count: 31 },
			{ id: 31, name: '孟伟', count: 77 },
			{ id: 45, name: '毛静', count: 25 },
			{ id: 58, name: '莫凡', count: 84 },
			{ id: 76, name: '穆琳', count: 42 }
		]
	},
	{
		type: 'p',
		list: [
			{ id: 11, name: '潘峰', count: 61 },
			{ id: 32, name: '彭雨', count: 13 },
			{ id: 46, name: '蒲铭', count: 72 },
			{ id: 59, name: '庞鑫', count: 53 },
			{ id: 77, name: '平超', count: 39 }
		]
	},
	{
		type: 's',
		list: [
			{ id: 12, name: '孙阳', count: 48 },
			{ id: 33, name: '宋雪', count: 21 },
			{ id: 47, name: '沈航', count: 97 },
			{ id: 60, name: '苏明', count: 63 },
			{ id: 78, name: '石磊', count: 27 },
			{ id: 87, name: '时雨', count: 91 }
		]
	},
	{
		type: 'w',
		list: [
			{ id: 13, name: '王峰', count: 56 },
			{ id: 34, name: '魏琪', count: 38 },
			{ id: 48, name: '吴洋', count: 75 },
			{ id: 61, name: '汪瀚', count: 24 },
			{ id: 79, name: '韦宁', count: 81 },
			{ id: 90, name: '武悦', count: 46 }
		]
	},
	{
		type: 'x',
		list: [
			{ id: 14, name: '徐杰', count: 93 },
			{ id: 35, name: '许萌', count: 16 },
			{ id: 62, name: '谢铭', count: 62 },
			{ id: 80, name: '夏宇', count: 54 },
			{ id: 89, name: '肖云', count: 28 },
			{ id: 92, name: '许锋', count: 36 }
		]
	},
	{
		type: 'y',
		list: [
			{ id: 63, name: '杨洋', count: 47 },
			{ id: 64, name: '余敏', count: 35 },
			{ id: 81, name: '袁磊', count: 64 },
			{ id: 83, name: '叶轩', count: 59 },
			{ id: 91, name: '岳琳', count: 22 }
		]
	},
	{
		type: 'z',
		list: [
			{ id: 65, name: '张伟', count: 29 },
			{ id: 66, name: '赵楠', count: 85 },
			{ id: 67, name: '周婷', count: 67 },
			{ id: 68, name: '郑昊', count: 44 },
			{ id: 69, name: '钟琪', count: 53 },
			{ id: 82, name: '朱琳', count: 38 },
			{ id: 85, name: '庄静', count: 21 },
			{ id: 86, name: '曾明', count: 65 },
			{ id: 93, name: '章华', count: 76 },
			{ id: 94, name: '詹宇', count: 17 }
		]
	}
]);
list1.value = list1.value.map((item) => ({
	letter: item.type,
	data: item.list
}));
list1.value = list1.value.map((group) => ({
	...group,
	data: group.data.map((student) => ({
		name: student.name,
		id: student.id,
		...student
	}))
}));
</script>

<style scoped>
.title {
	font-size: 18px;
	display: block;
	margin: 10px 0;
}
.start-btn {
	width: 100%;
	padding: 12px;
	background: #409eff;
	color: white;
	border: none;
	border-radius: 4px;
	font-size: 16px;
	margin: 20px 0;
}
.preview {
	margin-top: 20px;
}
.preview-img {
	width: 100%;
	height: 200px;
	margin-top: 10px;
	border: 1px solid #eee;
}
</style>
